import { oss_signature } from '@/services/getOssData';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, message, Upload } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { useEffect, useState } from 'react';
import { flushSync } from 'react-dom';

interface OSSDataType {
  dir: string;
  expire: string;
  host: string;
  accessid: string;
  policy: string;
  signature: string;
  callback?: string;
}

const AliyunOSSUpload = (props: any) => {
  const { imageUrl, setImageUrl, status } = props;
  const [loading, setLoading] = useState(false);
  const [OSSData, setOSSData] = useState<OSSDataType>();

  useEffect(() => {
    init();
  }, []);

  const init = async () => {
    try {
      const result = await oss_signature();
      flushSync(() => {
        setOSSData(result.data);
      });
    } catch (error: any) {
      message.error(error);
    }
  };

  const beforeUpload = async (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
      return false;
    }

    if (!OSSData) return false;

    const expire = Number(OSSData.expire) * 1000;
    if (expire < Date.now()) {
      await init();
    }
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = Date.now() + suffix;
    // @ts-ignore
    file.url = OSSData.dir + filename;

    return file;
  };
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log('info--------------', info);
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      setLoading(false);
      setImageUrl(OSSData?.host + '/' + info.file.url);
    }
  };
  /**
   *额外的上传参数
   * @param file
   * @returns
   */
  const getExtraData: UploadProps['data'] = async (file) => {
    let res = {
      key: file.url,
      OSSAccessKeyId: OSSData?.accessid,
      policy: OSSData?.policy,
      Signature: OSSData?.signature,
    };
    console.log(res);

    return res;
  };
  const uploadButton = <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>;

  return (
    <>
      <Button
        disabled={status}
        style={{ margin: '0', padding: '0', width: '100px', height: '100px' }}
        type="link"
      >
        <Upload
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action={OSSData?.host}
          data={getExtraData}
          beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          {imageUrl ? (
            <img src={imageUrl} alt="avatar" style={{ width: '100%', height: '100%' }} />
          ) : (
            uploadButton
          )}
        </Upload>
      </Button>
    </>
  );
};

export default AliyunOSSUpload;
